<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="出/入库单编号" prop="storageId">
        <el-input v-model="queryParams.storageId" placeholder="请输入出/入库单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期" prop="storageTime">
        <el-date-picker type="daterange" v-model="storageTime" format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd" :style="{width: '100%'}" start-placeholder="开始日期" end-placeholder="结束日期"
                        range-separator="至" clearable @change="handleDateChange"></el-date-picker>
      </el-form-item>
      <el-form-item label="入库对账类型" prop="recoTypeIn">
        <el-select v-model="queryParams.recoTypeIn" placeholder="请选择对账类型" clearable>
          <el-option label="采购入库" value="采购入库" />
          <!-- <el-option label="采购退货" value="采购退货" /> -->
          <el-option label="次品入库" value="次品入库" />
          <!-- <el-option label="次品出库" value="次品出库" /> -->
          <!-- <el-option label="调拨出库" value="调拨出库" /> -->
          <!-- <el-option label="发货出库" value="发货出库" /> -->
          <!-- <el-option label="返工领料" value="返工领料" /> -->
          <el-option label="客供入库" value="客供入库" />
          <!-- <el-option label="领料出库" value="领料出库" /> -->
          <!-- <el-option label="盘盈出库" value="盘盈出库" /> -->
          <el-option label="盘盈入库" value="盘盈入库" />
          <!-- <el-option label="其他出库" value="其他出库" /> -->
          <el-option label="其他入库" value="其他入库" />
          <!-- <el-option label="生产补料" value="生产补料" /> -->
          <!-- <el-option label="生产领料" value="生产领料" /> -->
          <el-option label="生产入库" value="生产入库" />
          <!-- <el-option label="生产损耗" value="生产损耗" /> -->
          <el-option label="退料入库" value="退料入库" />
          <!-- <el-option label="销售出库" value="销售出库" /> -->
          <el-option label="销售退货" value="销售退货" />
          <!-- <el-option label="研发领料" value="研发领料" /> -->
          <el-option label="研发入库" value="研发入库" />
          <!-- <el-option label="样品出库" value="样品出库" /> -->
        </el-select>
      </el-form-item>
      <el-form-item label="出库对账类型" prop="recoTypeOut">
        <el-select v-model="queryParams.recoTypeOut" placeholder="请选择对账类型" clearable>
          <el-option label="采购退货" value="采购退货" />
          <el-option label="次品出库" value="次品出库" />
          <el-option label="调拨出库" value="调拨出库" />
          <el-option label="发货出库" value="发货出库" />
          <el-option label="返工领料" value="返工领料" />
          <el-option label="领料出库" value="领料出库" />
          <el-option label="盘盈出库" value="盘盈出库" />
          <el-option label="其他出库" value="其他出库" />
          <el-option label="生产补料" value="生产补料" />
          <el-option label="生产领料" value="生产领料" />
          <el-option label="生产损耗" value="生产损耗" />
          <el-option label="销售出库" value="销售出库" />
          <el-option label="研发领料" value="研发领料" />
          <el-option label="样品出库" value="样品出库" />
        </el-select>
      </el-form-item>
       <el-form-item label="物料编码" prop="itemCode">
          <el-input v-model="queryParams.itemCode" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="物料名称" prop="itemName">
          <el-input v-model="queryParams.itemName" placeholder="请输入物料名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="仓库" prop="itemWare">
          <el-select v-model="queryParams.itemWare" placeholder="请选择仓库" clearable>
            <el-option v-for="ware in warehouseOptions" :key="ware.value" :label="ware.label" :value="ware.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出/入库" prop="recoCondition">
          <el-select v-model="queryParams.recoCondition" placeholder="请选择出/入库" clearable>
            <el-option label="出库" value="出库" />
            <el-option label="入库" value="入库" />
            <el-option label="损耗" value="损耗" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
                <el-option label="已审核" value="已审核" />
                <el-option label="未审核" value="未审核" />
              </el-select>
            </el-form-item>
        <el-form-item label="对账状态" prop="recoStatus">
              <el-select v-model="queryParams.recoStatus" placeholder="请选择对账状态" clearable>
                <el-option label="已对账" value="已对账" />
                <el-option label="未对账" value="未对账" />
              </el-select>
        </el-form-item>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleBatchReview"
            v-hasPermi="['mes:reco:ckdz:batchReview']"
        >批量审核</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            icon="el-icon-tickets"
            size="mini"
            @click="handleBatchReconciliation"
            v-hasPermi="['mes:reco:ckdz:batchReconciliation']"
        >批量对账</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-refresh"
            size="mini"
            @click="handleSync"
            v-hasPermi="['mes:reco:repo:sync']"
        >数据同步</el-button>
      </el-col>
      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['mes:reco:ckdz:export']"
              >导出</el-button>
            </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repoDetailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="出/入库单编号" width="170" prop="storageId">
      </el-table-column>
      <el-table-column label="出/入库日期" width="95" prop="storageTime">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.storageTime) }}
        </template>
      </el-table-column>
      <el-table-column label="出/入库" width="70" prop="recoCondition" />
      <el-table-column label="采购/销售订单编号" width="160" prop="purcOrderCode">
        <template slot-scope="scope">
          <el-button type="text" @click="handleOrderInfoClick(scope.row)">
            {{ scope.row.purcOrderCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="对账类型" width="78" prop="recoType" />
      <el-table-column label="物料名称" width="200" prop="itemName" />
      <el-table-column label="物料编码" width="135" prop="itemCode" />
      <el-table-column label="出/入库数量" width="90" prop="itemNum" />
      <el-table-column label="单价" width="50" prop="itemUnitPrice" v-if="!isUserLitong" />
      <el-table-column label="单位" width="80" prop="itemUnit" />
      <el-table-column label="入库金额" width="100" prop="itemInPrice" v-if="!isUserLitong"/>
      <el-table-column label="出库金额" width="100" prop="itemOutPrice" v-if="!isUserLitong"/>
      <el-table-column label="仓管确认" width="75" prop="confName" />
      <el-table-column label="仓库" width="75" prop="itemWare" />
      <el-table-column label="审核人" width="75" prop="auditName" />
      <el-table-column label="审核时间" width="95" prop="auditTime">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.auditTime) }}
        </template>
      </el-table-column>
      <el-table-column label="审核状态" width="75" prop="auditStatus" fixed="right">
        <template slot-scope="scope">
          <span v-if="scope.row.auditStatus === '已审核'" style="color: green;">{{ scope.row.auditStatus }}</span>
          <el-button
              v-else
              type="text"
              size="mini"
              @click="handleReview(scope.row)"
          >审核</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="65" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.auditStatus === '已审核' && scope.row.recoStatus !== '已对账'"
              size="mini"
              type="text"
              @click="handleReconciliation(scope.row)"
          >对账</el-button>
          <span v-else-if="scope.row.recoStatus === '已对账'" style="color: gray;">已完成</span>
        </template>
      </el-table-column>
      <el-table-column label="对账日期" width="95" prop="recoTime" />
      <el-table-column label="对账人" width="75" prop="recoName" />
    </el-table>

    <!-- 采购订单信息弹窗 -->
    <el-dialog title="采购订单信息" :visible.sync="purchaseOrderDialogVisible" width="70%">
      <!-- 基本信息直接放在外层 -->
      <div style="margin-bottom: 20px;">
        <h4>基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="8"><strong>采购订单编号:</strong> {{ purchaseOrderMainData.purchase_order_number }}</el-col>
          <el-col :span="8"><strong>采购需求:</strong> {{ purchaseOrderMainData.procurement_demand }}</el-col>
          <el-col :span="8"><strong>订单日期:</strong> {{ purchaseOrderMainData.order_date }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>申请人:</strong> {{ purchaseOrderMainData.applicant }}</el-col>
          <el-col :span="8"><strong>申请部门:</strong> {{ purchaseOrderMainData.applicant_dept }}</el-col>
          <el-col :span="8"><strong>采购状态:</strong> {{ purchaseOrderMainData.procurement_status }}</el-col>
          <!-- <el-col :span="8"><strong>总金额:</strong> {{ purchaseOrderMainData.total_purchase_amount }}</el-col> -->
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>支付状态:</strong> {{ purchaseOrderMainData.payment_type }}</el-col>
          <el-col :span="8"><strong>支付方式:</strong> {{ purchaseOrderMainData.reimburse_type }}</el-col>

        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">


          <el-col :span="8"><strong>收款账户名:</strong> {{ purchaseOrderMainData.account_name }}</el-col>
          <el-col :span="8"><strong>银行卡号:</strong> {{ purchaseOrderMainData.bank_card_number }}</el-col>
        </el-row>
      </div>

      <!-- 物料明细保持在子表中 -->
      <div>
        <h4>物料明细</h4>
        <el-table :data="purchaseOrderItems" border>
          <el-table-column prop="purc_supplier_name" label="供应商名称"></el-table-column>
          <el-table-column prop="purc_supplier_code" label="供应商编码"></el-table-column>
          <el-table-column prop="purc_material_name" label="物料名称"></el-table-column>
          <el-table-column prop="purc_material_code" label="物料编码"></el-table-column>
          <el-table-column prop="purc_specifications" label="规格型号"></el-table-column>
          <!-- <el-table-column prop="purc_unit_price" label="单价"></el-table-column> -->
          <el-table-column prop="purc_quantity_demand" label="数量"></el-table-column>
          <el-table-column prop="purc_units" label="单位"></el-table-column>
        </el-table>
      </div>
      <div>
         <el-row :gutter="20" style="margin-top: 15px;">
              <el-col :span="8">
                <strong>入库时间:</strong>
                {{ purchaseOrderMainData.storage_time }}
              </el-col>
            </el-row>
        </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="purchaseOrderDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 销售订单信息弹窗 -->
    <el-dialog title="销售订单信息" :visible.sync="salesOrderDialogVisible" width="70%">
      <div style="margin-bottom: 20px;">
        <h4>基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="8"><strong>客户名称:</strong> {{ salesOrderMainData.customer_name }}</el-col>
          <el-col :span="8"><strong>订单编号:</strong> {{ salesOrderMainData.order_code }}</el-col>
          <el-col :span="8"><strong>签订日期:</strong> {{ salesOrderMainData.order_signing_date }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>销售负责人:</strong> {{ salesOrderMainData.sales_person }}</el-col>
          <!-- <el-col :span="8"><strong>合同总金额:</strong> {{ salesOrderMainData.total_contract_amount }}</el-col> -->
          <el-col :span="8"><strong>备注:</strong> {{ salesOrderMainData.remark }}</el-col>
        </el-row>
      </div>

      <div>
        <h4>产品明细</h4>
        <el-table :data="salesOrderItems" border>
          <el-table-column prop="product_name" label="产品名称"></el-table-column>
          <el-table-column prop="product_code" label="产品编码"></el-table-column>
          <el-table-column prop="specifications" label="规格型号"></el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <!-- <el-table-column prop="unit_price" label="单价"></el-table-column> -->
          <el-table-column prop="units" label="单位"></el-table-column>
          <!-- <el-table-column prop="amount" label="小计金额"></el-table-column> -->
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="salesOrderDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <!-- 生产损耗信息弹窗 -->
    <el-dialog title="生产损耗信息" :visible.sync="proLossDialogVisible" width="70%">
      <div style="margin-bottom: 20px;">
        <h4>基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="8"><strong>报损日期:</strong> {{ proLossMainData.report_date }}</el-col>
          <el-col :span="8"><strong>报损人:</strong> {{ proLossMainData.report_name }}</el-col>
          <el-col :span="8"><strong>部门:</strong> {{ proLossMainData.dept }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>原因:</strong> {{ proLossMainData.reason }}</el-col>
        </el-row>
      </div>

      <div>
        <h4>物料明细</h4>
        <el-table :data="proLossItems" border>
          <el-table-column prop="item_code" label="物料编码"></el-table-column>
          <el-table-column prop="item_name" label="物料名称"></el-table-column>
          <el-table-column prop="item_spec" label="规格型号"></el-table-column>
          <el-table-column prop="item_num" label="数量"></el-table-column>
          <el-table-column prop="item_unit" label="单位"></el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="proLossDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="常温报工信息" :visible.sync="proFeedbackDialogVisible" width="70%">
      <div style="margin-bottom: 20px;">
        <h4>基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="8"><strong>客户名称:</strong> {{ feedbackMainData.customer_name }}</el-col>
            <el-col :span="8"><strong>订单编号:</strong> {{ feedbackMainData.order_code }}</el-col>
            <el-col :span="8"><strong>签订日期:</strong> {{ feedbackMainData.order_signing_date }}</el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 10px;">
            <el-col :span="8"><strong>销售负责人:</strong> {{ feedbackMainData.sales_person }}</el-col>
            <!-- <el-col :span="8"><strong>合同总金额:</strong> {{ salesOrderMainData.total_contract_amount }}</el-col> -->
            <el-col :span="8"><strong>备注:</strong> {{ feedbackMainData.remark }}</el-col>
          </el-row>
        </div>

        <div>
          <h4>产品明细</h4>
          <el-table :data="feedbackSalesDetailList" border>
            <el-table-column prop="product_name" label="产品名称"></el-table-column>
            <el-table-column prop="product_code" label="产品编码"></el-table-column>
            <el-table-column prop="specifications" label="规格型号"></el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
            <!-- <el-table-column prop="unit_price" label="单价"></el-table-column> -->
            <el-table-column prop="units" label="单位"></el-table-column>
            <!-- <el-table-column prop="amount" label="小计金额"></el-table-column> -->
          </el-table>
        </div>
        <!-- <h4>基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="8"><strong>生产报工流水号:</strong> {{ feedbackMainData.scbg_code }}</el-col>
          <el-col :span="8"><strong>创建人:</strong> {{ feedbackMainData.creator }}</el-col>
          <el-col :span="8"><strong>创建时间:</strong> {{ formatDateTime(feedbackMainData.createTime) }}</el-col>
        </el-row>
      </div> -->

      <!-- <div style="margin-bottom: 20px;">
        <h4>报工单信息</h4>
        <el-row :gutter="20">
          <el-col :span="8"><strong>工单编号:</strong> {{ feedbackMainData.workorder_code }}</el-col>
          <el-col :span="8"><strong>产品名称:</strong> {{ feedbackMainData.product_name }}</el-col>
          <el-col :span="8"><strong>规格型号:</strong> {{ feedbackMainData.specification }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>订单日期:</strong> {{ formatDateTime(feedbackMainData.order_date, 'YYYY-MM-DD') }}</el-col>
          <el-col :span="8"><strong>订单总需求:</strong> {{ feedbackMainData.order_total_demand }}</el-col>
          <el-col :span="8"><strong>报工数量:</strong> {{ feedbackMainData.quantity_feedback }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>合格数量:</strong> {{ feedbackMainData.quantity_qualified }}</el-col>
          <el-col :span="8"><strong>不合格数量:</strong> {{ feedbackMainData.quantity_unquanlified }}</el-col>
          <el-col :span="8"><strong>批次号:</strong> {{ feedbackMainData.batch_number }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>工序名称:</strong> {{ feedbackMainData.process_name }}</el-col>
          <el-col :span="8"><strong>杀菌釜:</strong> {{ feedbackMainData.sterilization_kettle }}</el-col>
          <el-col :span="8"><strong>开始时间:</strong> {{ formatDateTime(feedbackMainData.start_time) }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>结束时间:</strong> {{ formatDateTime(feedbackMainData.end_time) }}</el-col>
          <el-col :span="8"><strong>耗时(分钟):</strong> {{ feedbackMainData.working_hours }}</el-col>
          <el-col :span="8"><strong>人均效率:</strong> {{ feedbackMainData.good_manhours }}</el-col>
        </el-row> -->
        <!-- <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>部门:</strong> {{ feedbackMainData.user_dept?.name }}</el-col>
          <el-col :span="8"><strong>提交时间:</strong> {{ formatDateTime(feedbackMainData.submission_time) }}</el-col>
        </el-row> -->
      <!-- </div> -->

      <!-- <div style="margin-bottom: 20px;">
        <h4>检验结果</h4>
        <p>{{ feedbackMainData.inspection_results }}</p>
      </div> -->

      <!-- <div v-if="feedbackMainData.picture_upload && feedbackMainData.picture_upload.length > 0">
        <h4>图片预览</h4>
        <div v-for="pic in feedbackMainData.picture_upload" :key="pic.url" style="display: inline-block; margin-right: 10px;">
          <img :src="pic.url" :alt="pic.name" style="width: 100px; height: auto;" />
        </div>
      </div> -->

      <div style="margin-bottom: 20px;">
        <h4>备注:</h4>
        <p>{{ feedbackMainData.remark || '无' }}</p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="proFeedbackDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>


    <el-dialog title="现金销售单信息" :visible.sync="cashSalesDialogVisible" width="70%">
      <div style="margin-bottom: 20px;">
        <h4>基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="8"><strong>订单编号:</strong> {{ cashSalesMainData.xjxs_code }}</el-col>
          <el-col :span="8"><strong>客户名称:</strong> {{ cashSalesMainData.cus_name }}</el-col>
          <el-col :span="8"><strong>创建人:</strong> {{ cashSalesMainData.creator }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>订单日期:</strong> {{ formatDateTime(cashSalesMainData.order_date) }}</el-col>
          <el-col :span="8"><strong>订单类型:</strong> {{ cashSalesMainData.order_type }}</el-col>
          <el-col :span="8"><strong>来源:</strong> {{ cashSalesMainData.product_source }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>销售数量:</strong> {{ cashSalesMainData.sale_num }}</el-col>
          <!-- <el-col :span="8"><strong>总金额:</strong> {{ cashSalesMainData._widget_1740367169984 }} 元</el-col> -->
          <el-col :span="8"><strong>收款状态:</strong> {{ cashSalesMainData._widget_1747706426203 }}</el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="8"><strong>备注:</strong> {{ cashSalesMainData.remark || '无' }}</el-col>
        </el-row>
      </div>

      <div>
        <h4>商品明细</h4>
        <el-table :data="cashSalesItems" border>
          <el-table-column prop="item_name" label="商品名称"></el-table-column>
          <el-table-column prop="item_code" label="商品编码"></el-table-column>
          <el-table-column prop="item_spec" label="规格型号"></el-table-column>
          <el-table-column prop="item_order_num" label="数量"></el-table-column>
          <!-- <el-table-column prop="item_unit_price" label="单价(元)"></el-table-column> -->
          <!-- <el-table-column prop="item_amount" label="小计金额(元)"></el-table-column> -->
          <el-table-column prop="item_ware" label="仓库"></el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cashSalesDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>







    <!-- 分页组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script>
import { getRecoRepoDetailList, reviewStep3, recoStep3, batchReview, batchReco, finaRecoRepoSync, getPurchaseOrderDetails,getSalesOrderListInfo ,getProLossListInfo,getProFeedbackListInfo,getProSdFeedbackListInfo,getCashSalesOrderListInfo,exportRepoData} from "@/api/mes/reco/ckdz";
import moment from 'moment';

export default {
  name: "FinaCkdz",
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storageId: null,
        storageTimeStart: null,
        storageTimeEnd: null,
        recoType: null,
        itemCode: null,     // 物料编码
        itemName: null,     // 物料名称
        itemWare: null,     // 仓库
        recoCondition: null,
        selectedRows: [],
        auditStatus: null,  // 审核状态
        recoStatus: null    // 对账状态
      },
      warehouseOptions: [
        { label: '辅料仓', value: '辅料' },
        { label: '主料仓', value: '主料' },
        { label: '半成品仓', value: '半成品' },
        { label: '成品仓', value: '成品' },
        { label: '包材仓', value: '包材' },
        { label: '样品仓', value: '样品' },
        { label: '易耗品仓', value: '易耗品' },
        { label: '添加剂仓', value: '添加剂' },
        { label: '前处理仓', value: '前处理' },
        { label: '其他', value: '其他' },
      ],
      storageTime: [],
      repoDetailList: [],
      total: 0,
      loading: false,
      showSearch: true,
      purchaseOrderDialogVisible: false,
      purchaseOrderMainData: {}, // 主信息
      purchaseOrderItems: []    ,// 物料明细
      salesOrderDialogVisible: false,
      salesOrderMainData: {},
      salesOrderItems: [],
      proLossDialogVisible: false,
      proLossMainData: {},
      proLossItems: [],
      proFeedbackDialogVisible: false,
      feedbackMainData: {},
      feedbackSalesDetailList: [],
      cashSalesDialogVisible: false,
      cashSalesMainData: {},
      cashSalesItems: []

    };
  },
  computed: {
      // 计算属性判断是否为 litong 用户
      isUserLitong() {
        return this.currentUser === 'litong';
      }
    },
  created() {
    this.currentUser = this.$store?.getters?.name || localStorage.getItem('username') || '';
    this.setDefaultToday();
    this.getList();
  },
  methods: {
    handleOrderInfoClick(row) {
          const recoType = row.recoType;
          const orderCode = row.purcOrderCode;
          const itemWare = row.itemWare;

          if (recoType === '采购入库') {
            this.getPurchaseOrderInfo(orderCode);
          } else if (recoType === '发货出库') {
            this.getSalesOrderInfo(orderCode);
          } else if (recoType === '生产损耗') {
            this.getProLossInfo(orderCode);
          }else if (recoType === '生产入库') {
            if (itemWare.includes('常温')) {
                  this.getProFeedbackInfo(orderCode); // 调用常温报工接口
                } else if (itemWare.includes('速冻')) {
                  this.getProSdFeedbackInfo(orderCode); // 调用速冻报工接口
                } else {
                  this.$message.warning('仓库类型不明确，无法确定调用哪个报工接口');
                }
          } else if (recoType === '销售出库') {
            this.getCashSalesOrderInfo(orderCode);
          }else {
            this.$message.warning('暂不支持查看该类型订单详情');
          }
        },
    getPurchaseOrderInfo(purcOrderCode) {
      console.log('点击的 purcOrderCode:', purcOrderCode);
      this.purchaseOrderDialogVisible = true;

      getPurchaseOrderDetails(purcOrderCode).then(response => {
        const innerData = response.data?.data; // 注意这里多了一层 .data
        console.log('解析后的采购详情:', innerData);

        if (!innerData) {
          this.$message.error("接口返回数据为空");
          return;
        }

        this.purchaseOrderMainData = {
          purchase_order_number: innerData.purchase_order_number || '',
          procurement_demand: innerData.procurement_demand || '',
          order_date: moment(innerData.order_date).format('YYYY-MM-DD'),
          applicant: innerData.applicant?.name || '',
          applicant_dept: innerData.applicant_dept?.name || '',
          total_purchase_amount: innerData.total_purchase_amount || 0,
          payment_type: innerData.payment_type || '',
          account_name: innerData.account_name || '',
          bank_card_number: innerData.bank_card_number || '',
          procurement_status: innerData.procurement_status || '',
          reimburse_type: innerData.reimburse_type || '',
          storage_time: moment(innerData.storage_time).format('YYYY-MM-DD HH:mm:ss')
        };

        const productList = innerData.purchase_product_list || [];
        this.purchaseOrderItems = productList.map(item => ({
          purc_supplier_name: item.purc_supplier_name || '',
          purc_supplier_code: item.purc_supplier_code || '',
          purc_material_name: item.purc_material_name || '',
          purc_material_code: item.purc_material_code || '',
          purc_specifications: item.purc_specifications || '',
          purc_unit_price: item.purc_unit_price || 0,
          purc_quantity_demand: item.purc_quantity_demand || 0,
          purc_units: item.purc_units || ''
        }));

      }).catch(error => {
        this.$message.error("获取采购订单信息失败");
        console.error("获取采购订单信息错误:", error);
      });
    },
    getSalesOrderInfo(salesOrderCode) {
      console.log('点击的 salesOrderCode:', salesOrderCode);
      this.salesOrderDialogVisible = true;

      getSalesOrderListInfo(salesOrderCode).then(response => {
        const innerData = response.data?.data; // 注意多了一层 data

        if (!innerData) {
          this.$message.error("接口返回数据为空");
          return;
        }

        // 提取主表数据
        this.salesOrderMainData = {
          customer_name: innerData.cus_name || innerData.contract_party_a || '无',
          order_code: innerData.order_code || '',
          order_signing_date: moment(innerData.order_signing_date).format('YYYY-MM-DD') || '',
          total_contract_amount: innerData.total_contract_amount || 0,
          sales_person: innerData.person_in_charge?.name || '',
          remark: innerData.remark || ''
        };

        // 提取子表数据
        const productList = innerData.sales_detail_list || [];
        this.salesOrderItems = productList.map(item => ({
          product_name: item.sales_product_name || '',
          product_code: item.sales_product_code || '',
          specifications: item.sales_spec || '',
          quantity: item.sales_num || 0,
          unit_price: item.sales_price || 0,
          units: item.sales_unit || '',
          amount: item.sales_amount || 0
        }));

      }).catch(error => {
        this.$message.error("获取销售订单信息失败");
        console.error("获取销售订单信息错误:", error);
      });
    },
    getProLossInfo(orderCode) {
      console.log('点击的生产损耗单编号:', orderCode);
      this.proLossDialogVisible = true;

      getProLossListInfo(orderCode).then(response => {
        const data = response.data?.data;
        if (!data) {
          this.$message.error("接口返回数据为空");
          return;
        }

        // 解析主表信息
        this.proLossMainData = {
          report_date: moment(data.report_date).format('YYYY-MM-DD'),
          report_name: data.report_name?.name,
          dept: data.dept?.name,
          reason: data.reason || '无'
        };

        // 解析物料明细
        const items = data.item_list || [];
        this.proLossItems = items.map(item => ({
          item_code: item.item_code || '',
          item_name: item.item_name || '',
          item_spec: item.item_spec || '',
          item_num: item.item_num || 0,
          item_unit: item.item_unit || ''
        }));
      }).catch(error => {
        this.$message.error("获取生产损耗信息失败");
        console.error("获取生产损耗信息错误:", error);
      });
    },
    // getProFeedbackInfo(proId) {
    //   console.log('点击的 proId:', proId);
    //   this.proFeedbackDialogVisible = true;

    //   getProFeedbackListInfo(proId).then(response => {
    //     const data = response.data?.data;
    //     if (!data) {
    //       this.$message.error("接口返回数据为空");
    //       return;
    //     // 解析主表信息
    //     this.feedbackMainData = {
    //       scbg_code:data.scbg_code,
    //       creator: data.creator.name,
    //       createTime: data.createTime,
    //       // updater: data.updater,
    //       // updateTime: data.updateTime,
    //       // flowState: data.flowState,
    //       workorder_code: data.workorder_code,
    //       product_name: data.product_name,
    //       specification: data.specification,
    //       order_date: data.order_date,
    //       order_total_demand: data.order_total_demand,
    //       quantity_feedback: data.quantity_feedback,
    //       quantity_qualified: data.quantity_qualified,
    //       quantity_unquanlified: data.quantity_unquanlified,
    //       batch_number: data.batch_number,
    //       process_name: data.process_name,
    //       sterilization_kettle: data.sterilization_kettle,
    //       start_time: data.start_time,
    //       end_time: data.end_time,
    //       working_hours: data.working_hours,
    //       good_manhours: data.good_manhours,
    //       // user_dept: data.user_dept,
    //       // submission_time: data.submission_time,
    //       inspection_results: data.inspection_results,
    //       // picture_upload: data.picture_upload,
    //       remark: data.remark
    //     };
    //   }).catch(error => {
    //     this.$message.error("获取常温报工信息失败");
    //     console.error("获取常温报工信息错误:", error);
    //   });
    // },
    getProFeedbackInfo(proId) {
      console.log('点击的 proId:', proId);
      this.proFeedbackDialogVisible = true;

      getProFeedbackListInfo(proId).then(response => {
        const data = response.data?.data;
        if (!data) {
          this.$message.error("接口返回数据为空");
          return;
        }

        // 提取主表数据
        this.feedbackMainData = {
          customer_name: data.cus_name || data.contract_party_a || '无',
          order_code: data.order_code || '',
          order_signing_date: moment(data.order_signing_date).format('YYYY-MM-DD') || '',
          total_contract_amount: data.total_contract_amount || 0,
          sales_person: data.person_in_charge?.name || '',
          remark: data.remark || ''
        };

        // 提取子表数据
        const productList = data.sales_detail_list || [];
        this.feedbackSalesDetailList = productList.map(item => ({
          product_name: item.sales_product_name || '',
          product_code: item.sales_product_code || '',
          specifications: item.sales_spec || '',
          quantity: item.sales_num || 0,
          unit_price: item.sales_price || 0,
          units: item.sales_unit || '',
          amount: item.sales_amount || 0
        }));

      }).catch(error => {
        this.$message.error("获取常温报工信息失败");
        console.error("获取常温报工信息错误:", error);
      });
    },
    getProSdFeedbackInfo(proId) {
      console.log('点击的 proId:', proId);
      this.proFeedbackDialogVisible = true;

      getProSdFeedbackListInfo(proId).then(response => {
        const data = response.data?.data;
        if (!data) {
          this.$message.error("接口返回数据为空");
          return;
        }

        // 提取主表数据
        this.feedbackMainData = {
          customer_name: data.cus_name || data.contract_party_a || '无',
          order_code: data.order_code || '',
          order_signing_date: moment(data.order_signing_date).format('YYYY-MM-DD') || '',
          total_contract_amount: data.total_contract_amount || 0,
          sales_person: data.person_in_charge?.name || '',
          remark: data.remark || ''
        };

        // 提取子表数据
        const productList = data.sales_detail_list || [];
        this.feedbackSalesDetailList = productList.map(item => ({
          product_name: item.sales_product_name || '',
          product_code: item.sales_product_code || '',
          specifications: item.sales_spec || '',
          quantity: item.sales_num || 0,
          unit_price: item.sales_price || 0,
          units: item.sales_unit || '',
          amount: item.sales_amount || 0
        }));

      }).catch(error => {
        this.$message.error("获取常温报工信息失败");
        console.error("获取常温报工信息错误:", error);
      });
    },
    // getProSdFeedbackInfo(proId) {
    //   console.log('点击的 proId:', proId);
    //   this.proFeedbackDialogVisible = true;

    //   getProSdFeedbackListInfo(proId).then(response => {
    //     const data = response.data?.data;
    //     if (!data) {
    //       this.$message.error("接口返回数据为空");
    //       return;
    //     }

    //     // 解析主表信息
    //     this.feedbackMainData = {
    //       scbg_code:data.scbg_code,
    //       creator: data.creator.name,
    //       createTime: data.createTime,
    //       // updater: data.updater,
    //       // updateTime: data.updateTime,
    //       // flowState: data.flowState,
    //       workorder_code: data.workorder_code,
    //       product_name: data.product_name,
    //       specification: data.specification,
    //       order_date: data.order_date,
    //       order_total_demand: data.order_total_demand,
    //       quantity_feedback: data.quantity_feedback,
    //       quantity_qualified: data.quantity_qualified,
    //       quantity_unquanlified: data.quantity_unquanlified,
    //       batch_number: data.batch_number,
    //       process_name: data.process_name,
    //       sterilization_kettle: data.sterilization_kettle,
    //       start_time: data.start_time,
    //       end_time: data.end_time,
    //       working_hours: data.working_hours,
    //       good_manhours: data.good_manhours,
    //       // user_dept: data.user_dept,
    //       // submission_time: data.submission_time,
    //       inspection_results: data.inspection_results,
    //       // picture_upload: data.picture_upload,
    //       remark: data.remark
    //     };
    //   }).catch(error => {
    //     this.$message.error("获取速冻报工信息失败");
    //     console.error("获取速冻报工信息错误:", error);
    //   });
    // },
    getCashSalesOrderInfo(orderCode) {
      console.log('点击的现金销售单编号:', orderCode);
      this.cashSalesDialogVisible = true;

      getCashSalesOrderListInfo(orderCode).then(response => {
        const data = response.data?.data;
        if (!data) {
          this.$message.error("接口返回数据为空");
          return;
        }

        // 解析主表信息
        this.cashSalesMainData = {
          xjxs_code: data.xjxs_code,
          cus_name: data.cus_name,
          creator: data.creator.name,
          order_date: data.order_date,
          order_type: data.order_type,
          product_source: data.product_source,
          sale_num: data.sale_num,
          _widget_1740367169984: data._widget_1740367169984,
          receipt_status: data.receipt_status,
          remark: data.remark
        };

        // 解析子表数据
        const items = data.item_details || [];
        this.cashSalesItems = items.map(item => ({
          item_name: item.item_name,
          item_code: item.item_code,
          item_spec: item.item_spec,
          item_order_num: item.item_order_num,
          item_unit_price: item.item_unit_price,
          item_amount: item.item_amount,
          item_ware: item.item_ware
        }));

      }).catch(error => {
        this.$message.error("获取现金销售单信息失败");
        console.error("获取现金销售单信息错误:", error);
      });
    },
    setDefaultToday() {
      const today = moment().format('YYYY-MM-DD');
      this.storageTime = [today, today];
      this.queryParams.storageTimeStart = today;
      this.queryParams.storageTimeEnd = today;
    },
    getList() {
      this.loading = true;
      getRecoRepoDetailList(this.queryParams).then(response => {
        this.repoDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    handleSync() {
      if (this.loading) {
        this.$modal.message("正常进行中，请不要重复点击...");
        return;
      }
      this.loading = true;
      this.$modal.confirm('是否确认同步数据？').then(() => {
        finaRecoRepoSync().then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("同步成功");
            this.getList();
          } else {
            this.$modal.msgError("同步失败");
          }
        }).catch(() => {
          this.$modal.msgError("同步失败");
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    handleReview(row) {
      this.$confirm('是否确认审核？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reviewStep3(row).then(res => {
          if (res.code === 200) {
            this.$message.success("审核成功");
            this.getList();
          } else {
            this.$message.error(res.msg || "审核失败");
          }
        }).catch(() => {
          this.$message.info("操作已取消");
        });
      });
    },
    handleReconciliation(row) {
      this.$confirm('是否确认对账？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        recoStep3(row).then(res => {
          if (res.code === 200) {
            this.$message.success("对账成功");
            this.getList();
          } else {
            this.$message.error("对账失败");
          }
        }).catch(() => {
          this.$message.info("操作已取消");
        });
      });
    },
    handleBatchReview() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      }

      this.$confirm('是否确认批量审核所选数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedRows.map(row => String(row.ckdzSubId));
        batchReview(ids).then(res => {
          if (res.code === 200) {
            this.$message.success("批量审核成功");
            this.getList();
          } else {
            this.$message.error(res.msg || "批量审核失败");
          }
        });
      }).catch(() => {
        this.$message.info("操作已取消");
      });
    },
    handleBatchReconciliation() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      }

      this.$confirm('是否确认批量对账所选数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedRows.map(row => String(row.ckdzSubId));
        batchReco(ids).then(res => {
          if (res.code === 200) {
            this.$message.success("批量对账成功");
            this.getList();
          } else {
            this.$message.error(res.msg || "批量对账失败");
          }
        });
      }).catch(() => {
        this.$message.info("操作已取消");
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.recoType = this.queryParams.recoTypeIn || this.queryParams.recoTypeOut || null;
      this.getList();
    },
    resetQuery() {
      this.queryParams.storageId = null;
      this.storageTime = [];
      this.queryParams.itemCode = null;
      this.queryParams.itemName = null;
      this.queryParams.itemWare = null;
      this.queryParams.recoCondition = null;
      this.queryParams.recoTypeIn = null;
      this.queryParams.recoTypeOut = null;
      this.queryParams.auditStatus = null;
      this.queryParams.recoStatus = null;
      this.handleQuery();
    },
    formatDateTime(date) {
      return date ? moment(date).format('YYYY-MM-DD') : '';
    },
    handleDateChange(val) {
      if (val && val.length >= 2) {
        this.queryParams.storageTimeStart = val[0];
        this.queryParams.storageTimeEnd = val[1];
      } else {
        this.queryParams.storageTimeStart = null;
        this.queryParams.storageTimeEnd = null;
      }
    },
    // 导出功能
    handleExport() {
      this.$confirm('是否确认导出数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 创建不带分页的查询参数
        const exportQuery = { ...this.queryParams };
        delete exportQuery.pageNum;
        delete exportQuery.pageSize;

        return exportRepoData(exportQuery);
      }).then(response => {
        // 处理导出响应
        this.download(response, '仓库对账列表数据.xlsx');
        this.$message.success('导出成功');
      }).catch((error) => {
        console.error('导出失败:', error);
        this.$message.error('导出失败');
      });
    },

    // 下载文件方法
    download(response, filename) {
      const blob = new Blob([response], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      link.click();
      window.URL.revokeObjectURL(url);
    }

  }
};
</script>

<style scoped>
.el-table-column {
  white-space: nowrap;
}
</style>
